/**
 * Copyright (c) 2010 CWI Amsterdam and others. All rights reserved.
 * This program and the accompanying materials are made available
 * under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *    CWI Amsterdam - initial API and implementation
 */
package nl.cwi.arne.ui.actions;

import nl.cwi.arne.diagram.part.ArneDiagramEditor;
import nl.cwi.arne.ui.ArneUIPlugin;
import nl.cwi.arne.ui.jobs.GenerateActivationsJob;

import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchSite;

/**
 * @author Christian Krause
 */
public class GenerateActivationsAction extends Action {
	
	public static ImageDescriptor START_JOB_ICON = ArneUIPlugin.getImageDescriptor("/icons/StartActivationsJob.gif");
	public static ImageDescriptor STOP_JOB_ICON = ArneUIPlugin.getImageDescriptor("/icons/StopActivationsJob.gif");
	
	// Workbench site.
	private IWorkbenchSite site;
	
	// Job for generating activations.
	private GenerateActivationsJob generateJob;
	
	/**
	 * Constructor.
	 */
	public GenerateActivationsAction(IWorkbenchSite site) {
		String name = "Generate Activations";
		setText(name);
		setToolTipText(name);
		setImageDescriptor(START_JOB_ICON);
		this.site = site;
		this.generateJob = new GenerateActivationsJob();
		this.generateJob.addJobChangeListener(jobAdapter);
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.eclipse.jface.action.Action#run()
	 */
	@Override
	public void run() {
		if (generateJob.getState()==Job.RUNNING) {
			generateJob.cancel();
		} else {		
			IEditorPart editor = site.getPage().getActiveEditor();
			if (editor instanceof ArneDiagramEditor) {
				generateJob.setEditor((ArneDiagramEditor) editor);
				generateJob.schedule();
			}
		}
	}
	
	/*
	 * Job adapter.
	 */
	private JobChangeAdapter jobAdapter = new JobChangeAdapter() {

		/* 
		 * (non-Javadoc)
		 * @see IJobChangeListener#scheduled(IJobChangeEvent)
		 */
		public void scheduled(IJobChangeEvent event) {
			Display.getDefault().asyncExec(new Runnable() {
				public void run() {
					setImageDescriptor(STOP_JOB_ICON);
				}
			});
		}

		/*
		 * (non-Javadoc)
		 * @see org.eclipse.core.runtime.jobs.JobChangeAdapter#done(org.eclipse.core.runtime.jobs.IJobChangeEvent)
		 */
		public void done(IJobChangeEvent event) {
			Display.getDefault().asyncExec(new Runnable() {
				public void run() {
					setImageDescriptor(START_JOB_ICON);
				}
			});
		}

	};
	
}
